﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Utilities.Core.Text;

namespace Systematize.Data.EntityFramework.Context
{
    public class SystematizeDbContext : DbContext, IDbContextAsync
    {
        public SystematizeDbContext()
            : base("Systematize")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var configurationTypes = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(type => type.Namespace.IsNotEmpty() &&
                               type.BaseType != null &&
                               type.BaseType.IsGenericType &&
                               type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

            foreach (Type type in configurationTypes)
            {
                dynamic configInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configInstance);
            }

            base.OnModelCreating(modelBuilder);
        }

        DbEntityEntry<TEntity> IDbContext.Entry<TEntity>(TEntity entity)
        {
            return Entry(entity);
        }

        IDbSet<TEntity> IDbContext.Set<TEntity>()
        {
            return Set<TEntity>();
        }

        Task<int> IDbContextAsync.SaveChangesAsync()
        {
            return base.SaveChangesAsync();
        }
    }
}
